package com.zhuozhou.jdyc.api;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Network;
import android.os.Bundle;
import android.os.Environment;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.MutableLiveData;

import com.baidu.mapapi.SDKInitializer;
import com.zhuozhou.jdyc.broadcastreceiver.NetworkStateReceiver;
import com.zhuozhou.jdyc.main.base.activity.FingerViewActivity;
import com.zhuozhou.jdyc.main.base.activity.LockViewActivity;
import com.zhuozhou.jdyc.util.apiUtil.FileUtils;
import com.zhuozhou.jdyc.util.apiUtil.NotificationUtils;
import com.zhuozhou.jdyc.util.crash.CrashHandler;
import com.zhuozhou.jdyc.util.log.LogUtil;
import com.zhuozhou.jdyc.util.log.LogcatHelper;
import com.zhuozhou.jdyc.welcome.LaunchActivity;
import com.zhuozhou.jdyc.welcome.StartActivity;
import com.zhuozhou.jdyc.welcome.WelcomeActivity;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import io.reactivex.plugins.RxJavaPlugins;

/**
 * Created by 方舟 on 2017/6/20.
 * Application
 */

public class ApplicationHelper extends Application implements Application.ActivityLifecycleCallbacks {
    private boolean isBackGround;
    private static ApplicationHelper applicationHelper;
    public final static String ACTION_INTENT_RECEIVER = "android.net.conn.CONNECTIVITY_CHANGE";
    public final static String ACTION_INTENT_RECEIVER_8 = "android.net.wifi.SCAN_RESULTS";

    private NetworkStateReceiver networkChangeReceiver;
    private MutableLiveData<Network> mutableLiveData = new MutableLiveData<>();
    private MutableLiveData<String> mutableLiveDataError = new MutableLiveData<>();
    private IntentFilter intentFilter;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (networkChangeReceiver != null) {
            unregisterReceiver(networkChangeReceiver);
        }
    }

    private void initNetWorkReceiver() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_INTENT_RECEIVER);
        intentFilter.addAction(ACTION_INTENT_RECEIVER_8);
        networkChangeReceiver = new NetworkStateReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    public MutableLiveData<Network> getMutableLiveData() {
        return mutableLiveData;
    }

    public MutableLiveData<String> getMutableLiveDataError() {
        return mutableLiveDataError;
    }

    private void startLockView() {
        Intent intent = new Intent(this, LockViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    private void startFingerLockView() {
        Intent intent = new Intent(this, FingerViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    public static ApplicationHelper getInstance() {
        return applicationHelper;
    }

    private void initFile() {
        if (FileUtils.hasSdcard()) {
            FileUtils.makeDirs(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + ConstantsHelper.ROOTFILEPATH + File.separator + "crash" + File.separator);
            FileUtils.makeDirs(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + ConstantsHelper.ROOTFILEPATH + File.separator + "log" + File.separator);
        }
    }

    /**
     * 全局捕获crash并保存日志到本地
     */
    private void initLogCrash() {
        CrashHandler.getInstance().init(getApplicationContext());
    }

    private void init() {
        applicationHelper = this;
        UserAccountHelper.init(this);
        AppSettingHelper.init(this);
        SDKInitializer.initialize(getApplicationContext());
        initNetWorkReceiver();
        initLogCrash();
        RxJavaPlugins.setErrorHandler(e -> mutableLiveDataError.setValue(null));
        initFile();
        LogcatHelper.getInstance(this).start();
        LogUtil.init();
        NotificationUtils.init(this);
    }

    public NetworkStateReceiver getNetworkChangeReceiver() {
        return networkChangeReceiver;
    }

    @Override
    public void onActivityCreated(@NotNull Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(@NotNull Activity activity) {
    }

    @Override
    public void onActivityResumed(@NotNull Activity activity) {
        if (isBackGround) {
            isBackGround = false;
//                    Integer userId = null;
//                    String phoneCode = null;
//                    if (UserAccountHelper.isLogin()) {
//                        userId = Integer.valueOf(UserAccountHelper.getUserId() + "");
//                        phoneCode = UserAccountHelper.getUser().getTelphone();
//                    }
//                    AccessLog.upDataLog(getApplicationContext(),"APP回到了前台");
            LogUtil.show("APP回到了前台");
            if (!AppManager.isActivityTop(LockViewActivity.class, activity) &&
                    (activity.getClass() != LaunchActivity.class) &&
                    (activity.getClass() != WelcomeActivity.class) &&
                    (activity.getClass() != FingerViewActivity.class) &&
                    (activity.getClass() != StartActivity.class)) {
                if (AppSettingHelper.getGesturesIsOpen())
                    startLockView();
                else if (AppSettingHelper.getFingerIsOpen())
                    startFingerLockView();
            }
        }
    }

    @Override
    public void onActivityPaused(@NotNull Activity activity) {
    }

    @Override
    public void onActivityStopped(@NotNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(@NotNull Activity activity) {

    }

    @Override
    public void onTrimMemory(int level) {

        if (level == TRIM_MEMORY_UI_HIDDEN) {
            isBackGround = true;
//            Integer userId = null;
//            String phoneCode = null;
//            if (UserAccountHelper.isLogin()) {
//                userId = Integer.valueOf(UserAccountHelper.getUserId() + "");
//                phoneCode = UserAccountHelper.getUser().getTelphone();
//            }
            LogUtil.show("APP遁入后台");
//            AccessLog.upDataLog(getApplicationContext(),"APP遁入后台");
        }
        super.onTrimMemory(level);
    }

    public static int getColors(int id) {
        return ContextCompat.getColor(applicationHelper, id);

    }
}
